import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:go_router/go_router.dart';
import 'package:leader_doctor_flutter/common/data/app.dart';
import 'package:leader_doctor_flutter/common/http/api.dart';
import 'package:leader_doctor_flutter/common/http/http_client.dart';
import 'package:leader_doctor_flutter/common/utils/image_utils.dart';
import 'package:leader_doctor_flutter/common/utils/string_utils.dart';
import 'package:leader_doctor_flutter/common/widget/comm_widget.dart';
import 'package:leader_doctor_flutter/router/router.dart';
import 'package:leader_doctor_flutter/styles/colors.dart';
import 'package:netease_meeting_ui/meeting_ui.dart';

class WalletSetPasswordPage extends StatefulWidget {
  const WalletSetPasswordPage({super.key});

  @override
  State<WalletSetPasswordPage> createState() => _WalletSetPasswordPageState();
}

class _WalletSetPasswordPageState extends State<WalletSetPasswordPage> {
  final _pwdTextEditingController = TextEditingController();

  bool _isShowEye = false;

  @override
  void initState() {
    super.initState();
    _pwdTextEditingController.addListener(() {
      setState(() {});
    });
  }

  @override
  Widget build(BuildContext context) {
    return contentView();
  }

  Widget contentView() {
    return Scaffold(
      appBar: CommWidget.getCommAppbar(context),
      body: Container(
        color: Colors.white,
        width: double.infinity,
        height: double.infinity,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Container(
              padding: EdgeInsets.only(
                  left: 15.w, right: 15.w, top: 15.w, bottom: 15.w),
              color: ColorRes.colorEDEDFD,
              child: Text(
                "注：为了您的账户隐私安全，请设置访问密码，遗忘密码将无法查看账户信息，请妥善保存！",
                style: TextStyle(fontSize: 13.sp, color: ColorRes.color333333),
              ),
            ),
            SizedBox(
              height: 10.w,
            ),
            Container(
              padding: EdgeInsets.only(
                left: 15.w,
                right: 15.w,
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  _buildPasswordTextField(),
                  CommWidget.buildLine(),
                  SizedBox(height: 52.w),
                  _buildSubmitButton(),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 输入新密码栏
  Widget _buildPasswordTextField() {
    return SizedBox(
      height: 50.w,
      width: double.infinity,
      child: Row(
        children: [
          Expanded(
            child: TextField(
              controller: _pwdTextEditingController,
              keyboardType: TextInputType.number,
              inputFormatters: [
                LengthLimitingTextInputFormatter(6),
                FilteringTextInputFormatter.allow(RegExp(r'[0-9a-zA-Z]')),
              ],
              obscureText: !_isShowEye,
              decoration: const InputDecoration(
                hintText: '请输入新密码',
                border: InputBorder.none,
              ),
            ),
          ),
          GestureDetector(
            onTap: () {
              _isShowEye = !_isShowEye;
              setState(() {});
            },
            child: ImageLoader.loadAsset(
              _isShowEye ? 'icon_eye.webp' : 'icon_eye_close.webp',
              20.w,
            ),
          ),
        ],
      ),
    );
  }

  /// 提交按钮
  Widget _buildSubmitButton() {
    var isSelectBtn = _pwdTextEditingController.text.isNotEmpty;

    return CommWidget.buildRightBtn('确定', () => _setWalletPwd(),
        isSelect: isSelectBtn);
  }

  /// 修改密码
  _setWalletPwd() async {
    var pwd = _pwdTextEditingController.text;
    if (pwd.length < 6) {
      ToastUtils.showToast(context, '请输入6位纯数字的安全码');
      return;
    }
    var id = App.instance.userInfo?.id;
    if (id == null || id.isEmpty == true) return;
    var httpRequest = HttpRequest(Api.walletSetPwd, urlParams: {
      "userMedicalId": id,
      'safeCode': StringUtils.dartMd5(pwd),
    });
    var httpResponse = await HttpClient.get(httpRequest);
    var serviceResult = ServiceResult<String?>.simple(httpResponse);
    print("设置钱包密码 = $serviceResult");
    ToastUtils.showToast(context, serviceResult.responseMsg);
    if (serviceResult.success) {
      FocusScope.of(context).unfocus();
      context.pushReplacement(PageUrl.walletPwd);
    }
  }
}
